package com.cancan.demo.apidebouncing.exception;

import com.cancan.demo.apidebouncing.response.HttpCodeEnum;
import com.cancan.demo.apidebouncing.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 统一异常处理
 */
@RestControllerAdvice
@Slf4j
public class ExceptionController {

    /**
     * 捕捉业务相关异常
     */
    @ExceptionHandler(TokenException.class)
    public JsonResult handle401(HttpServletResponse response, TokenException e) {
        response.setStatus(HttpCodeEnum.UNAUTHORIZED.getCode());
        log.error("异常{}的信息为：{}", HttpCodeEnum.UNAUTHORIZED.getCode(),e.getMessage());
        return new JsonResult(HttpCodeEnum.UNAUTHORIZED.getCode(), e.getMessage(), null);
    }


    /**
     * 捕捉业务相关异常
     */
    @ExceptionHandler(BusinessException.class)
    public JsonResult handle10000(BusinessException e) {
        log.error("异常{}的信息为：{}", HttpCodeEnum.BUSINESS_ERROR.getCode(),e.getMessage());
        return new JsonResult(HttpCodeEnum.BUSINESS_ERROR.getCode(), e.getMessage(), null);
    }


    /**
     * 捕捉参数异常的异常
     */
    @ExceptionHandler(ParamException.class)
    public JsonResult handle10002(ParamException e) {
        log.error("异常{}的信息为：{}",HttpCodeEnum.PARAM_ERROR.getCode(),e.getMessage());
        return new JsonResult(HttpCodeEnum.PARAM_ERROR.getCode(), e.getMessage(), null);
    }

    /**
     * 捕捉其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public JsonResult globalException(HttpServletRequest request, Throwable e) {
        log.error("异常{}的信息为：{}",HttpCodeEnum.SERVER_ERROR.getCode(),e.getMessage());
        return new JsonResult(getStatus(request).value(), "系统错误", null);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}